import recordRegistry from '../../shared/RecordRegistry.js'
import roleManager from '../../shared/RoleManager.js'
import signatureClaim from '../../shared/SignatureClaim.js'

export const fetchRecords = async (req) => {
    if (!req.session.user) {
        return res.status(401).json({ error: '未授权访问' });
    }

    const { page = 1, size = 5, filter, searchTerm } = req.query;
    const pageNum = parseInt(page);
    const pageSize = parseInt(size);

    try {
        // 1. 获取所有记录ID（单次合约调用）
        let allRecordIds = searchTerm
            ? await recordRegistry.methods.getRecordByIdNumber(searchTerm).call()
            : await recordRegistry.methods.getAllRecordId().call();

        // 2. 批量获取所有记录的状态（用于筛选）
        const filteredRecordIds = await Promise.all(
            allRecordIds.map(async (recordId) => {
                let record, medicalType;
                let status = -1;

                record = await recordRegistry.methods.getRecord(recordId).call();

                try {
                    const status = await signatureClaim.methods.checkSignature(recordId).call()
                } catch (error) { }

                return {
                    recordId,
                    status: Number(status),
                    medicalType: Number(record.medicalType)
                };
            })
        );

        let matchedRecords = filteredRecordIds;
        if (filter) {
            matchedRecords = matchedRecords.filter(item => item.status === Number(filter));
        }
        if (type === 'hospital') {
            matchedRecords = matchedRecords.filter(item => item.medicalType !== 2);
            console.log("医院记录：", matchedRecords)
        } else {
            console.log("实验室记录：", matchedRecords)
            matchedRecords = matchedRecords.filter(item => item.medicalType === 2);
            console.log("实验室记录：", matchedRecords)
        }

        const totalCount = matchedRecords.length;

        // 4. 计算分页范围
        const start = (pageNum - 1) * pageSize;
        const end = Math.min(start + pageSize, totalCount);

        // 5. 只获取当前页需要的记录ID
        const pageRecordIds = matchedRecords.slice(start, end).map(item => item.recordId);

        // 6. 批量获取当前页的记录数据
        const records = await Promise.all(
            pageRecordIds.map(async (recordId) => {
                const record = await recordRegistry.methods.getRecord(recordId).call();
                return {
                    id: recordId,
                    patientName: record.patientName,
                    idNumber: record.patientId,
                    date: record.date,
                    medicalType: Number(record.medicalType),
                    applyAmount: record.applyAmount.toString(),
                    applyReason: record.applyReason,
                    status: matchedRecords.find(item => item.recordId === recordId)?.status || -1
                };
            })
        );

        res.json({
            success: true,
            records: records,
            pagination: {
                currentPage: pageNum,
                pageSize: pageSize,
                totalItems: totalCount,
                totalPages: Math.ceil(totalCount / pageSize)
            }
        });

    } catch (error) {
        console.error('获取记录错误:', error);
        res.status(500).json({
            success: false,
            message: '获取记录失败'
        });
    }

}